//var UserData = require('UserData')
var sec_to_time = require('timeConvert')
var resLoader = require('./../function/resLoader')
var restaurantClass = require('restaurantClass')
var restaurants = require('restaurants')
//var chefClass = require('chefClass')
var COMMON_VALUE = require('Common')
let customers = require('customers')
let CUSTOMER_DATA = require('CustomerData')
import UserData from 'UserData'

cc.Class({
    extends: cc.Component,
    properties: {
        restaurantType: {
            default: COMMON_VALUE.RESTAURANT_TYPE.NONE,
            type: COMMON_VALUE.RESTAURANT_TYPE
        },
        moneyLabelPrefab: {
            default: null,
            type: cc.Prefab
        },
        chefData: null,
        level: 1,
        floor: null,
        resColor: "NONE",
        upgradeAudioClip: {
            default: null,
            type: cc.AudioClip
        },
        coinGetAudioClip: {
            default: null,
            type: cc.AudioClip
        },

        setUpAudioClip: {
            default: null,
            type: cc.AudioClip
        },
        buyResAudioClip: {
            default: null,
            type: cc.AudioClip
        },
    },
    initialize() { //餐厅的默认状态
        //console.log("restaurant.init",this.floor)
        this.promptShowed = false
        this.resSetup = false
        this.chefButton.interactable = this.resSetup
        this.qualityUpgradeList = []
        this.level = 1
        this.gainEverySec = false
        if (this.chefData && this.chefData != 1) {
            this.chefEnabled = true
            let offset = COMMON_VALUE.CHEF_AVATAR_OFFSET[parseInt(this.chefData.basicData.chefID) - 1]
            let chefphoto = this.node.getChildByName('Status Bar').getChildByName('头像框').getChildByName('Chef Photo')
            chefphoto.x = offset[0]
            chefphoto.y = offset[1]
            let AvatarSprite = this.node.getChildByName('Status Bar').getChildByName('头像框').getChildByName('Chef Photo').getComponent(cc.Sprite)
            resLoader.plistLoader("Chef/Avatar/头像plist", this.chefData.basicData.chefID, AvatarSprite)
        } else {
            this.chefEnabled = false
        }
        this.star = 0
        let k = 1.5
        if (this.floor <= 5) {
            k = 1.5 * Math.pow(2, this.floor - 1)
        } else if (this.floor <= 8 && this.floor > 5) {
            k = 1.5 * Math.pow(2, 4) * Math.pow(4, this.floor - 4)
        } else if (this.floor <= 10 && this.floor > 8) {
            k = 1536 * Math.pow(2, this.floor - 8)
        }
        this.originalTotalTime = k//Math.pow(2,Math.floor(this.floor)) * (Math.pow(2,Math.floor((this.floor-1)/6)))

        this.totalTime = this.originalTotalTime //总时间设置
        this.timeLeft = this.totalTime
        this.moneyPerProduct = this.upgradeManager.getCurrentGain()
        this.upgradeMultiplier = 1
        this.customerLimit = 2
        this.chefChooseList = []

        this.upgradeManager.level = this.level
        //获取质量升级列表，星星数每达到5就提升一级质量
        this.checkButtonStatus()
        this.updateDisplay()

    },
    updateResRuntimeData() {
        /////////////////////////////////////更新餐厅星级设定
        //1.餐厅升级时检测
        //2.餐厅升级的进度条更新+餐厅星星数的增长+餐厅质量牌子的贴图
        //3.餐厅时间减少，显示状态及totalTime
        //4.时间减到1秒以下时的计算
        //5.餐厅升级进度的（弹出，还有几级可升级or减少xxx）提示
        //2.
        //更新升级进度条的进度
        let lastLevel = 0
        let nextLevel = 0
        let starNum = 0
        let qualityLevel = 0
        let nextLevelBuff = 1

        if (this.level < this.upgradeManager.gainMultiplierList[0][0]) {
            nextLevel = this.upgradeManager.gainMultiplierList[0][0]
        } else {
            for (let i = 0; i < this.upgradeManager.gainMultiplierList.length - 1; i++) {
                if (this.level >= this.upgradeManager.gainMultiplierList[i][0]) {
                    starNum += 1
                }
                if (this.upgradeManager.gainMultiplierList[i][0] == this.qualityUpgradeList[qualityLevel]) {//
                    qualityLevel += 1
                    starNum = 0
                }
                if (this.upgradeManager.gainMultiplierList[i][0] <= this.level && this.upgradeManager.gainMultiplierList[i + 1][0] > this.level) {
                    lastLevel = this.upgradeManager.gainMultiplierList[i][0]
                    nextLevel = this.upgradeManager.gainMultiplierList[i + 1][0]
                    nextLevelBuff = this.upgradeManager.gainMultiplierList[i + 1][1]
                    break
                }
            }
        }
        let qualityChanged = false
        if (this.previousQualityLevel != qualityLevel) {
            this.previousQualityLevel = qualityLevel
            qualityChanged = true
        }

        let percent = (this.level - lastLevel) / (nextLevel - lastLevel)

        this.upgradeProgressBar.getChildByName('bar').runAction(cc.scaleTo(2, percent, 1).easing(cc.easeExponentialOut()))

        //更新星星数
        for (let j = 0; j < this.starList.length; j++) {
            if (j < starNum) {
                let playAnime = false
                if (!this.starList[j].active) {
                    playAnime = true
                }
                this.starList[j].active = true
                if (playAnime) {
                    this.starList[j].scaleX = 0
                    this.starList[j].scaleY = 0
                    this.starList[j].runAction(cc.scaleTo(0.5, 1, 1).easing(cc.easeElasticInOut()))
                    this.promptShowed = false
                }
            } else {
                this.starList[j].active = false
            }
        }
        //更新贴纸贴图

        if (this.textureOrder != qualityLevel + 1) {
            this.textureOrder = qualityLevel + 1
            if (this.textureOrder > 10) {
                this.textureOrder = 10
            } else if (this.textureOrder < 0) {
                this.textureOrder = 0
            }
            this.statusBackground = this.node.getChildByName('Status Bar').getComponent(cc.Sprite)
            this.avatarBackground = this.node.getChildByName('Status Bar').getChildByName('头像框').getComponent(cc.Sprite)

            this.node.getChildByName('Status Bar').runAction(cc.sequence(cc.scaleTo(0.2, 0, 0), cc.callFunc(() => {
                resLoader.plistLoader('Restaurant/UI/状态栏底色', this.textureOrder.toString(), this.statusBackground)
                resLoader.plistLoader('Restaurant/UI/状态栏底色', "avatar" + this.textureOrder.toString(), this.avatarBackground)
            }, this), cc.scaleTo(0.4, 1, 1).easing(cc.easeElasticOut())))


        }

        //3.餐厅星星数的增长+餐厅时间减少，同时更新餐厅现有生产进度条及显示状态及totalTime

        this.totalTime = this.originalTotalTime / Math.pow(2, qualityLevel)

        if (qualityChanged) {//如果总时间缩短了，当前进度也同步往前推
            let ratio = this.totalTime / this.originalTotalTime
            this.timeLeft = this.timeLeft * ratio
        }

        //4. 总时间在0.5秒以下的计算
        if (this.totalTime < 0.5 && this.gainEverySec == false) {
            this.progressBar.getChildByName('进度条遮罩').getChildByName('斑马').active = true
            this.progressBar.getChildByName('进度条遮罩').getChildByName('斑马').runAction(cc.sequence(
                cc.moveBy(0.5, cc.v2(60, 0)),
                cc.callFunc((self) => {
                    self.x = 0
                }, this)
            )).repeatForever()

            this.gainEverySec = true
        }
        //5.餐厅升级进度的（弹出，还有几级可升级or减少xxx）提示
        let per = (nextLevel - lastLevel) === 0 ? 0 : (this.level - lastLevel) / (nextLevel - lastLevel)
        let prompt = this.node.getChildByName('Status Bar').getChildByName('购买升级提示')
        if ((per >= 0.9 || (nextLevel - this.level < 10) && nextLevel != 0) && prompt.active === false && this.promptShowed === false) {
            prompt.zIndex = 201
            this.promptShowed = true
            prompt.scaleX = 0
            prompt.scaleY = 0
            prompt.getChildByName('label').getComponent(cc.Label).string = "再购买" + (nextLevel - this.level) + "级 收益x" + nextLevelBuff
            prompt.active = true
            prompt.runAction(cc.sequence(cc.scaleTo(0.5, 1, 1).easing(cc.easeExponentialOut()),
                cc.delayTime(3),
                cc.scaleTo(0.5, 0, 0).easing(cc.easeExponentialOut()),
                cc.callFunc(() => {
                prompt.active = false
            })))

        }
    },
    showResHideItem(node) {//未启用
        //用于升级餐厅时把餐厅里的对应等级的物品显形
        if (node.name.search("-l") != -1) {
            cc.log(node.name)
        }
        if (node.children.length = 0) {
            return
        } else {
            for (let i = 0; i < node.children.length; i++) {
                this.showResHideItem(node.children[i])
            }

        }
    },
    loadUserData(res) {
        //console.log('Restaurant.loadUserData',this.floor)
        if (this.floor) {
            if (res) {
                this.resData = res
                this.node.getComponent('ResSetup').start()
                this.node.getComponent('ResSetup').setupResTypeStr = res.restaurantType
                this.node.getComponent('ResSetup').setupRes(true, this.resData)

                //载入chefData
                this.chefData = res.chefData
                //
                if (this.chefData) {
                    this.chefEnabled = true
                    let offset = COMMON_VALUE.CHEF_AVATAR_OFFSET[parseInt(this.chefData.basicData.chefID) - 1]
                    let chefphoto = this.node.getChildByName('Status Bar').getChildByName('头像框').getChildByName('Chef Photo')
                    chefphoto.x = offset[0]
                    chefphoto.y = offset[1]
                    resLoader.plistLoader("Chef/Avatar/头像plist", this.chefData.basicData.chefID, chefphoto.getComponent(cc.Sprite))


                    this.node.getChildByName('Status Bar').getChildByName('Chef').active = false
                    this.node.getChildByName('Status Bar').getChildByName('头像框').active = true
                    this.node.getChildByName('Status Bar').getChildByName('Chef').getComponent(cc.Button).interactable = false
                } else {
                    this.chefEnabled = false
                }
            }

        }
    },
    startWork(ResSetupClick) {
        if (this.level === 0) {
            this.level = 1
            this.levelLabel.getComponent(cc.Label).string = "Lv." + this.level
            restaurants.setRestaurant(0, this.floor, { level: 1 }).then((res) => {
                cc.log(res)
            })
        }
        this.checkButtonStatus()
        this.updateBuffMoney()

        if (this.gainEverySec) {
            this.UserData.addCurrentMoney(this.buffMoney / 10)//因为每0.1秒更新一次
        } else {
            if (ResSetupClick != "ResSetup") {
                this.UserData.addCurrentMoney(this.buffMoney)
            }
        }
        this.checkButtonStatus()

        //载入上次进度条进度
        if (this.UserData.state.restaurantList[this.floor - 1]) {
            if (this.UserData.state.restaurantList[this.floor - 1].etime) {
                let lastTime = UserData.state.restaurantList[this.floor - 1].etime
                if (this.chefEnabled) {//有主厨
                    this.timeLeft = this.totalTime - lastTime % totalTime
                    //上传这次开始的进度
                    restaurants.setRestaurant(0, this.floor, { startTime: this.timeLeft }).then((res) => {
                        cc.log(res)
                    })
                } else {//没有主厨
                    if (this.totalTime > lastTime) {//没跑完一次
                        this.timeLeft = this.totalTime - lastTime
                    } else {//跑完一次
                        this.timeLeft = 0.5
                    }
                }
            } else {
                if (this.totalTime > 30) {//三十秒以上的在任务开始的时候上传进度为1秒
                    restaurants.setRestaurant(0, this.floor, { startTime: 1 }).then((res) => {
                        //cc.log(res)
                    })
                }
                this.timeLeft = this.totalTime
            }
            if (!this.UserData.state.restaurantList[this.floor - 1].calcOfflineFinished) {
                this.calcOfflineGain()
            }
            UserData.state.restaurantList[this.floor - 1].etime = null
        } else {
            this.timeLeft = this.totalTime
        }

        this.moneyPerSec = this.node.getComponent('UpgradeManager').getCurrentGain() / this.totalTime
        this.updateDisplay()
        this.waitAccountSprite.getComponent(cc.Button).interactable = false
        this.waitAccountSprite.runAction(cc.sequence(cc.fadeOut(0.1), cc.callFunc(() => {
            this.waitAccountSprite.active = false
            this.waitAccountSprite.opacity = 0
        })))
        //收益蹦字动画+xxx
        if (!this.gainEverySec) {
            let gainMoneyLabel = cc.instantiate(this.moneyLabelPrefab)
            gainMoneyLabel.getComponent('labelFixed').setNumber(this.buffMoney, "+$")
            gainMoneyLabel.zIndex = 200
            this.node.getChildByName('Status Bar').insertChild(gainMoneyLabel)
            gainMoneyLabel.runAction(cc.sequence(cc.spawn(cc.moveBy(1.3, cc.v2(0, 130)).easing(cc.easeExponentialOut()), cc.fadeOut(2)), cc.callFunc((gainMoneyLabel) => {
                gainMoneyLabel.destroy()
            })))
        }
        //音效
        if (!UserData.runtimeState.muteSound) {
            if (this.totalTime > 10 || !this.chefEnabled) {
                cc.audioEngine.play(this.coinGetAudioClip, null, 0.6)
            }
        }

    },
    calcOfflineGain() {
        let res = this.UserData.state.restaurantList[this.floor - 1]
        if (res.etime) {
            let offMoney = this.moneyPerSec * res.etime
            switch (res.resColor.toUpperCase()) {
                case "RED":
                    offMoney = offMoney * 0.66666
                    break
                case "YELLOW":
                    offMoney = offMoney
                    break
                case "BLUE":
                    offMoney = offMoney * 13 / 24
                    break
                default:
            }
            if (!this.Open === false) {//当前处于没开门的状态应该做个补偿
                offMoney = offMoney * 2
            }

            res.offlineGain = offMoney  //按餐厅颜色衰减
        } else {
            res.offlineGain = 0
        }
        res.calcOfflineFinished = true//已经计算完本餐厅的离线收益
        let allFinishCalc = true
        for (let i = 0; i < this.UserData.state.restaurantList.length; i++) {
            let res = this.UserData.state.restaurantList[i]
            if (res) {
                if (!res.calcOfflineFinished) {
                    allFinishCalc = false
                }
            }
        }
        if (allFinishCalc) {
            this.node.parent.getComponent('PopOfflineGain').popWindow()
        }
    },
    updateBuffMoney() {
        /*try{*/
            this.getCodeComponent()
            if (this.gainEverySec) {
                this.buffMoney = this.node.getComponent('UpgradeManager').getCurrentGain() / this.totalTime
            } else {
                this.buffMoney = this.node.getComponent('UpgradeManager').getCurrentGain()
            }
    
            for (var i = 0; i < UserData.runtimeState.GainMultiplyList.length; i++) {//技能对餐厅的加成
                let sk = UserData.runtimeState.GainMultiplyList[i]
                if (sk.target === this.color) {
                    this.buffMoney = this.buffMoney * sk.effectValue
                }
            }
            // 主厨对餐厅的加成-----------待修改--------//从远程载入并填入
            if (this.UserData && this.chefData) {
                for (var i = 0; i < this.UserData.state.restaurantList.length; i++) {
                    if (this.UserData.state.restaurantList[i]) {
                        if (this.UserData.state.restaurantList[i].floor === this.floor) {
                            this.chefData = this.UserData.state.restaurantList[i].chefData
                            let mul = null
                            for (let j = 0; j < this.chefData.chefRadar.length; j++) {
                                if (this.chefData.chefRadar[j].name == this.UserData.state.restaurantList[this.floor - 1].restaurantType) {
                                    mul = this.chefData.chefRadar[i].value / 100 + 1
                                    break
                                }
                            }
                            this.buffMoney = this.buffMoney * (mul ? mul : 1)
                        }
                    }
                }
            }
    
            //餐厅开业对buffMoney的加成
            let reputationRatio = 1
            this.buffMoney = this.buffMoney * (1 + (UserData.getReputation() > 0 ? UserData.getReputation() : 0) / 100 * reputationRatio)
            if (this.Open === false) {
                this.buffMoney = this.buffMoney * 0.5
            }
            if (this.gainEverySec) {
                this.moneyPerSec = this.buffMoney
            } else {
                this.moneyPerSec = this.buffMoney / this.totalTime
            }
            // 购买的buff列表对餐厅的加成
            let buffList = UserData.state.moneyBuffList
            if (buffList) {
                for (let i = 0; i < buffList.length; i++) {
                    if(buffList[i]){
                        if (this.floor === buffList[i].target || this.resColor.toUpperCase() === buffList[i].target || buffList[i].target === 'ALL') {
                            this.buffMoney = this.buffMoney * buffList[i].times
                        }
                    }
                }
            }
    
            buffList = UserData.state.reputationBuffList
            if (buffList) {
                for (let i = 0; i < buffList.length; i++) {
                    if(buffList[i]){
                        if (this.floor === buffList[i].target || this.resColor.toUpperCase() === buffList[i].target || buffList[i].target === 'ALL') {
                            this.buffMoney = this.buffMoney * buffList[i].times
                        }
                        this.buffMoney = this.buffMoney * buffList[i].times
                    }
                }
            }
            // 更新GPS
    
            this.GPS = this.buffMoney / this.totalTime
            if (this.resSetup === true) {
                UserData.runtimeState.GPSList[this.floor - 1] = this.GPS
            } else {
                UserData.runtimeState.GPSList[this.floor - 1] = 0
            }
            UserData.runtimeState.updateGPS(UserData.getCurrentMoney())
        /*}catch(err){
            if(this.err!=err){
                this.err =err
            }
        }*/
        
    },
    productFinish() {//收益完成时调用的函数
        if (this.resSetup) {
            if (this.chefEnabled) {
                this.startWork()
            } else {
                this.waitAccountSprite.active = true
                this.waitAccountSprite.getComponent(cc.Button).interactable = true
                this.waitAccountSprite.opacity = 255
                this.waitAccountSprite.getChildByName('点击结账').stopAction()
                this.waitAccountSprite.getChildByName('点击结账').getComponent('ElasticBump').bump()
            }
        }
    },
    setTimeBar(totalTime, timeLeft) {
        if (!this.gainEverySec) {
            this.gainTime = totalTime
            let progressPercentage = (totalTime - timeLeft) / totalTime
            this.progressBar.getChildByName('进度条遮罩').getChildByName('bar').width = this.barMaxWidth * progressPercentage
            this.timeLabel.getComponent('labelFixed').string = sec_to_time(this.timeLeft)
        } else {
            this.progressBar.getChildByName('进度条遮罩').getChildByName('bar').width = this.barMaxWidth
            this.timeLabel.active = false
        }
    },
    updateDisplay() {
        this.updateBuffMoney()
        if (this.Open == true) {
            if (this.gainEverySec) {
                this.GainLabel.getComponent("labelFixedRichText").setNumber(this.moneyPerSec, "<color=#DD5555>$", '/s ▲</c>')
            } else {
                this.GainLabel.getComponent("labelFixedRichText").setNumber(this.buffMoney, "<color=#DD5555>$", " ▲</c>")
            }
        } else {
            if (this.gainEverySec) {
                this.GainLabel.getComponent("labelFixedRichText").setNumber(this.moneyPerSec, "$", '/s')
            } else {
                this.GainLabel.getComponent("labelFixedRichText").setNumber(this.buffMoney, "$", "")
            }
        }

    },
    checkButtonStatus(node) {
        if (!node) {
            node = this
        }
        let upgradeResult = node.upgradeManager.calcUpgrade(node.upgradeMultiplier, node.UserData.getCurrentMoney())
        if (node.resSetup) {
            node.button.getComponent(cc.Button).interactable = upgradeResult[2]
            if (node.upgradeManager.getLevelUpCost(node.upgradeMultiplier, node.UserData.getCurrentMoney())[0] === 0) {
                node.CostLabel.getComponent('labelFixed').setNumber(node.upgradeManager.getLevelUpCost(1, node.UserData.getCurrentMoney())[0], "$")
            } else {
                node.CostLabel.getComponent('labelFixed').setNumber(node.upgradeManager.getLevelUpCost(node.upgradeMultiplier, node.UserData.getCurrentMoney())[0], "$")
            }
        } else {
            node.button.getComponent(cc.Button).interactable = false
        }
        return node.button.getComponent(cc.Button).interactable
    },
    upgrade() {
        //计算升级后是否还能买，不能买button置disable
        this.upgradeMultiplier = UserData.runtimeState.multiplyTimes
        let calResult = this.upgradeManager.calcUpgrade(this.upgradeMultiplier, this.UserData.getCurrentMoney())
        if (calResult[2]) {
            let originLevel = this.level
            this.level += calResult[1]
            this.upgradeManager.upgrade(calResult[1])
            this.moneyPerProduct = this.upgradeManager.getCurrentGain()
            this.moneyPerSec = this.moneyPerProduct / this.totalTime
            this.UserData.subCurrentMoney(calResult[0])
            //更新level数据显示
            this.node.getComponent('ResPlayableComponent').labelNumberChange(this.levelLabel, this.level, originLevel, "Lv.")
            //this.levelLabel.getComponent(cc.Label).string = "Lv." + this.level

            this.CostLabel.getComponent('labelFixed').setNumber(calResult[0], "$")
            this.checkButtonStatus()
            this.updateDisplay()

            //更新远程数据
            let startTime = 0
            if (this.timeLeft >= 1) {
                startTime = this.timeLeft
            } else {
                startTime = 1
            }
            restaurants.setRestaurant(0, this.floor, { level: this.level, startTime: startTime }).then((res) => {
                //cc.log(res)
            }).catch(err => cc.log(err))
            //更新本地数据
            this.UserData.state.restaurantList[this.floor - 1].Level = this.level
            this.updateResRuntimeData()
            //播放声音
            if (!this.UserData.runtimeState.muteSound) {
                cc.audioEngine.play(this.upgradeAudioClip, false, 0.3)
            }


            // 检测餐厅升级等级, 达到累计值发送请求获得用户~
            this.UserData.state.restaurantTotalLevels+=calResult[1]
            let check = false
            CUSTOMER_DATA.LIST.forEach((item) => {
                if (this.UserData.acquiredCustomersList && this.UserData.acquiredCustomersList.includes(item.id)) {
                    return
                } else if (item.condition === 'restaurantLevel' && this.UserData.state.restaurantTotalLevels >= item.conditionValue) {
                    // 向服务器发送添加客户id请求
                    customers.appendCustomer(item.id)
                }
            })

            //教程
            if(this.floor ==1 && this.node.getComponent('UpgradeManager').level >=10){
                if(!this.UserData.runtimeState.tutorialProgress.sideButton){
                    this.UserData.runtimeState.guide.guide = this.UserData.runtimeState.guide.TutorialArray.sideButton
                    this.UserData.runtimeState.guide.next()
                }
            }

            if(this.floor ==4 && this.node.getComponent('UpgradeManager').level >=1){
                if(!this.UserData.runtimeState.tutorialProgress.chefNode){
                    this.UserData.runtimeState.guide.guide = this.UserData.runtimeState.guide.TutorialArray.chefNode
                    this.UserData.runtimeState.guide.next()
                }
            }

            if(this.floor ==5 && this.node.getComponent('UpgradeManager').level >=100){
                if(!this.UserData.runtimeState.tutorialProgress.sellBuildingNode){
                    this.UserData.runtimeState.guide.guide = this.UserData.runtimeState.guide.TutorialArray.sellBuildingNode
                    this.UserData.runtimeState.guide.next()
                }
            }
            
            return true
        } else {//disable   
            return false
        }
    },
    checkOpenStatus(labelContent) {
        if (this.Open && this.resSetup) { //没有设置OPEN和open为true的时候都默认开店
            this.node.getChildByName('打烊').active = true
            if (!this.node.getChildByName('打烊').getComponent('ActionIn')) {
                this.node.getChildByName('打烊').addComponent('ActionIn')
                this.node.getChildByName('打烊').getComponent('ActionIn').playAnime()
            }
            if (labelContent) {
                this.node.getChildByName('打烊').getChildByName("Label").getComponent(cc.Label).string = labelContent
            }
        } else {
            this.node.getChildByName('打烊').active = false
        }
    },
    //灯光控制
    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},  
    getCodeComponent(){
        this.starList = this.node.getChildByName('Status Bar').getChildByName('Level Pannel').getChildByName('Stars Bar Background').children.slice(0, 5)
        this.upgradeProgressBar = this.node.getChildByName('Status Bar').getChildByName('Level Pannel').getChildByName('Stars Bar Background').getChildByName('upgradeProgressBar')
        this.progressBar = this.node.getChildByName('Status Bar').getChildByName('Transparent').getChildByName('ProgressBar')
        this.button = this.node.getChildByName('Status Bar').getChildByName('button')
        this.timeLabel = this.progressBar.getChildByName('Time Label')
        this.GainLabel = this.progressBar.getChildByName('Money Label')
        this.chefButton = this.node.getChildByName('Status Bar').getChildByName('Chef').getComponent(cc.Button)
        this.levelLabel = this.node.getChildByName('Status Bar').getChildByName('Level Pannel').getChildByName('Level Label')
        this.UserData = UserData
        this.upgradeManager = this.node.getComponent('UpgradeManager')
        this.CostLabel = this.button.getChildByName('Money Label')
        this.waitAccountSprite = this.node.getChildByName('mask').getChildByName('等待结账-AnimationCancel')
    },
    start() {
        this.upLoadTaskTime = 0
        //设置餐厅常数，在餐厅的一次生命周期中不会发生变化的数值
        if (typeof (this.customerList) == "undefined") {
            this.customerList = []
        }
        this.node.getChildByName('Status Bar').zIndex = 100

        this.getCodeComponent()

        this.barMaxWidth = this.progressBar.width + 20
        this.progressBar.getChildByName('进度条遮罩').getChildByName('bar').width = 0
        //把数值更新加入到全局列表中
        this.UserData.runtimeState.buttonUpdateList.push([this.checkButtonStatus, this])
        this.UserData.updateButtonList()
        this.node.zIndex = 100
        if (!(this.node.getComponent('ResSetup').setupFinished === 1)) {//如果没用被ResSetup初始化过则初始化一次
            this.totalDifferTime = 0//0.04
            this.currentDifferTime = 0
            this.initialize()
        }
    },

    update(dt) {
        this.currentDifferTime += dt
        if (this.gainEverySec == false) {
            1
            //更新progressBar的百分比        
            if (this.currentDifferTime >= this.totalDifferTime && this.resSetup) {
                this.timeLeft -= this.currentDifferTime
                this.currentDifferTime = 0
                if (this.timeLeft <= 0) {
                    this.timeLeft = 0
                    if (!this.waitAccountSprite.active) {
                        this.productFinish()
                    }
                }
                this.setTimeBar(this.totalTime, this.timeLeft)
            }
        } else {
            if (this.currentDifferTime >= 0.1 && this.resSetup) {
                this.currentDifferTime = 0
                this.setTimeBar(this.totalTime, this.timeLeft)
                if (!this.waitAccountSprite.active) {
                    this.productFinish()
                }
            }
        }
        this.upLoadTaskTime += dt
        if (this.totalTime <= 30 && this.upLoadTaskTime >= 30) { //任务时间少于三十秒的每30秒上传一次
            this.upLoadTaskTime = 0
            restaurants.setRestaurant(0, this.floor, { startTime: 1 }).then((res) => {
                //cc.log(res)
            })
        }
    },
});
